//
//  TKIMGroupPhotoCell.m
//  TKPhotoSelectDemo
//
//  Created by liupm on 16/4/20.
//  Copyright © 2016年 liupm. All rights reserved.
//

#import "TKIMImageSelectCell.h"
#import "TKIMImagePickerDefinition.h"

@interface TKIMImageSelectCell()
@property(nonatomic,strong) UIImageView *photoImageView;

@end
@implementation TKIMImageSelectCell

- (instancetype)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self)
    {
        [self drawView];
    }
    return self;
}


-(void)drawView
{
    [self.contentView addSubview:self.photoImageView];
    if ([TKIMImagePickerSet shareInstance].allowsMultipleSelection)
    {
        [self.contentView addSubview:self.checkBox];
    }
}


/**
 *  @Author lpm, 16-04-20 22:04:35
 *
 *  @brief  赋值
 *
 *  @param model
 */
-(void)setModel:(TKIMPhotoModel *)model
{
    _model = model;
    if (model.isSelected)
    {
        _checkBox.selected = YES;
    }
    else
    {
        _checkBox.selected = NO;
    }
    _checkBox.hidden = model.isVideoType;
    dispatch_async(dispatch_get_global_queue(0, 0), ^{
        UIImage *image = _model.thumbImage;
        dispatch_async(dispatch_get_main_queue(), ^{
            self.photoImageView.image = image;
        });
    });
}


/**
 *  @Author lpm, 16-04-20 22:04:24
 *
 *  @brief  选中图片
 */
-(void)doCheck
{
    if (self.model.isSelected)
    {
        self.model.isSelected = NO;
        _checkBox.selected = NO;
    }
    else
    {
        self.model.isSelected = YES;
        _checkBox.selected = YES;
    }
    if (_delegate && [_delegate respondsToSelector:@selector(photo:isSelected:)])
    {
        [_delegate photo:self.model isSelected:self.model.isSelected];
    }
}

#pragma mark 属性

-(UIImageView *)photoImageView
{
    if (!_photoImageView)
    {
        _photoImageView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, self.frame.size.width, self.frame.size.height)];
        _photoImageView.contentMode = UIViewContentModeScaleAspectFill;
        _photoImageView.clipsToBounds = YES;
    }
    return _photoImageView;
}

-(UIButton *)checkBox
{
    if (!_checkBox)
    {
        CGFloat x = self.frame.size.width-35;
        _checkBox =  [[UIButton alloc] initWithFrame:CGRectMake(x, 0, 35, 35)];
        _checkBox.imageEdgeInsets = UIEdgeInsetsMake(5, 5, 5, 5);
        [_checkBox addTarget:self action:@selector(doCheck) forControlEvents:UIControlEventTouchUpInside];
        [_checkBox setImage:[UIImage imageNamed:TKIMPhotoName(@"photo_unchecked")] forState:UIControlStateNormal];
        [_checkBox setImage:[UIImage imageNamed:TKIMPhotoName(@"photo_unchecked")] forState: UIControlStateHighlighted];
        [_checkBox setImage:[UIImage imageNamed:TKIMPhotoName(@"photo_checked")] forState:UIControlStateSelected];
        [_checkBox setImage:[UIImage imageNamed:TKIMPhotoName(@"photo_checked")] forState:UIControlStateSelected | UIControlStateHighlighted];
    }
    return _checkBox;
}


@end
